﻿using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace apitest.Application.Test.Services
{
    public class SSHService : IDynamicApiController
    {
        public async Task T1()
        {
            const int port = 22;
            const string host = "192.168.220.129";
            const string username = "root";
            const string password = "sr123456";
            const string workingdirectory = "/aaa";
            string uploadfolder = @"D:\AstCode\src\frontEnd\Ast-PMS-Web\dist";

            Console.WriteLine("Creating client and connecting");



            using (var client = new SftpClient(host, port, username, password))
            {
                client.Connect();
                Console.WriteLine("Connected to {0}", host);
                await client.DeleteDirectoryAsync(workingdirectory);
                client.CreateDirectory(workingdirectory);
                client.ChangeDirectory(workingdirectory);
                Console.WriteLine("Changed directory to {0}", workingdirectory);

                UploadDirectory(client, uploadfolder, workingdirectory);

                //using (var fileStream = new FileStream(uploadfolder, FileMode.Open))
                //{
                //    Console.WriteLine("Uploading {0} ({1:N0} bytes)",
                //                        uploadfolder, fileStream.Length);
                //    client.BufferSize = 4 * 1024; // bypass Payload error large files
                //    client.UploadFile(fileStream, Path.GetFileName(uploadfolder));
                //}
            }
        }

        void UploadDirectory(SftpClient client, string localPath, string remotePath)
        {
            Console.WriteLine("Uploading directory {0} to {1}", localPath, remotePath);

            IEnumerable<FileSystemInfo> infos =
                new DirectoryInfo(localPath).EnumerateFileSystemInfos();
            foreach (FileSystemInfo info in infos)
            {
                if (info.Attributes.HasFlag(FileAttributes.Directory))
                {
                    string subPath = remotePath + "/" + info.Name;
                    if (!client.Exists(subPath))
                    {
                        client.CreateDirectory(subPath);
                    }
                    UploadDirectory(client, info.FullName, remotePath + "/" + info.Name);
                }
                else
                {
                    using (var fileStream = new FileStream(info.FullName, FileMode.Open))
                    {
                        Console.WriteLine(
                            "Uploading {0} ({1:N0} bytes)",
                            info.FullName, ((FileInfo)info).Length);

                        client.UploadFile(fileStream, remotePath + "/" + info.Name);
                    }
                }
            }
        }

    }
}
